package com.vj.router.server.grpc;

import com.vj.router.server.impl.RouterDeviceGatewayServiceImpl;
import com.vj.router.server.impl.RouterGatewayRegistryServiceImpl;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import jakarta.annotation.PreDestroy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
public class GrpcServerConfig {

    private Server server;

    @Bean
    public Server grpcServer(RouterDeviceGatewayServiceImpl deviceGatewayService,
                             RouterGatewayRegistryServiceImpl gatewayRegistryService) {
        try {
            // 构建 gRPC 服务器
            server = ServerBuilder.forPort(9090)
                    .addService(deviceGatewayService)
                    .addService(gatewayRegistryService)
                    .build();

            // 启动服务器
            server.start();
            System.out.println("gRPC Server started on port 9090");

            // 优雅关闭
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                System.out.println("Shutting down gRPC server...");
                this.stopServer();
            }));
        } catch (Exception e) {
            throw new RuntimeException("Failed to start gRPC server", e);
        }
        return server;
    }

    @PreDestroy
    public void stopServer() {
        if (server != null) {
            try {
                server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
                System.out.println("gRPC Server stopped.");
            } catch (InterruptedException e) {
                System.err.println("gRPC Server shutdown interrupted: " + e.getMessage());
            }
        }
    }
}
